package com.learn.springcloud.service;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * rabbit设置测试
 * @author lin
 * @version 1.0
 * @description: rabbit设置测试
 * @date 2024/4/16 12:36
 */
public class RabbitTest {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        //先进行一个exchange的创建，第三个true就是我们exchange的持久化
        channel.exchangeDeclare("myExchange","direct", true);
        //创建一个queue， 第二个参数true就是我们对queue的持久设置
        channel.queueDeclare("myQueue", true, false, false, null);
        //绑定exchange和queue
        channel.queueBind("myQueue","myExchange","myRKey");
        //发送消息
        byte[] msg = "Hello World!".getBytes(StandardCharsets.UTF_8);
        //目前我们的消息不是持久化的消息，如果想要进行持久化，需要对我买的basicProperties进行一个设置，delivery_mode
        //设置成2，就说明消息的持久化
        channel.basicPublish("myExchange", "myRKey", false,
                new AMQP.BasicProperties().builder()
                        .deliveryMode(2)
                        .contentType("text/plain")
                        .build(), msg);
    }
}
